package com.lxs.spring6.boot3.schedule;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;

@Service
public class ScheduleTask implements SchedulingConfigurer {
    @NacosValue(value = "${schedule.cron:0/10 * * * * ?}", autoRefreshed = true)
    private String cron;
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                System.err.println("Current time： " + LocalDateTime.now());
            }
        }, new Trigger() {

            @Override
            public Instant nextExecution(TriggerContext triggerContext) {
                // 使用CronTrigger触发器，可动态修改cron表达式来操作循环规则
                CronTrigger cronTrigger = new CronTrigger(cron);
                return cronTrigger.nextExecution(triggerContext);
            }
        });
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }
}